package modules.lock.producers3;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock的 生产者和消费者
 * 票 - 资源类
 *    if 改为while即可，防止虚假唤醒
 *    condition.await();  等待
 *    condition.signalAll();  通知其他线程
 * @author shengren.yan
 * @create 2021-03-05
 */
public class Ticket4 {

    private int number = 0;

    // Lock版本的 生产者与消费
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    // +1
    public void increment(){
        lock.lock(); //加锁
        try {
            while (number!=0){
                try {
                    condition.await(); //等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "执行："+ number);
            condition.signalAll(); // 通知其他线程
        } finally {
            lock.unlock(); //解锁
        }
    }

    // -1
    public synchronized void decrement(){
        lock.lock(); //加锁
        try {
            while(number==0){
                try {
                    condition.await(); //等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "执行："+ number);
            condition.signalAll(); // 通知其他线程
        } finally {
            lock.unlock(); //解锁
        }
    }


}